package com.xinnet.mms.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.area.service.AreaService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customerstate.service.CustomerStateHistService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.Area;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerCare;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.login.service.EmpService;
import com.xinnet.mms.order.service.OrderService;
import com.xinnet.mms.product.service.ProductService;
import com.xinnet.mms.role.service.RoleService;
import com.xinnet.mms.utils.CustomerManage;

@Controller
@RequestMapping("/util")
public class UtilController {
	SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Autowired
	EmpCustomRelationService empCustomRelationService;
	@Autowired
	CustomAllotService customAllotService;
	@Autowired
	ProductService productService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private EmpService empService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private CustomerStateHistService customerStateHistService;
	@Autowired
	private OrderService orderService;
	
	private String sep=java.io.File.separator;
	/**
	 * 
	 * 功能描述：跳转导入客户页面
	 *
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@RequestMapping("/leading")
	public String showLeading() {
		return "market/util/leading";
	}
	/**
	 * 
	 * 功能描述：上传
	 *
	 * @param request
	 * @param response
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws Exception 
	 * @throws IllegalStateException 
	 * @since 2014年2月24日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@RequestMapping("/upload")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	public String uploadLeading(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "pic", required = false) MultipartFile pic) throws Exception {
		//上传部分
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
		NoticeController noticeController=new NoticeController();
		String picName = pic.getOriginalFilename();
		picName=noticeController.makeName(picName);
		path=noticeController.makePath(picName, path);
		pic.transferTo(new File(path,picName));
		
		Customer customer=new Customer();
		//POI读取部分
		String doName=picName.substring(picName.lastIndexOf(".")+1).toLowerCase();
		//EXCEL2007以前版本
		if(doName.equals("xls")) {
			HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(path+picName));
			HSSFSheet sheet=workbook.getSheetAt(0);
			for(int i=1;i<=sheet.getLastRowNum();i++) {
				HSSFRow hrow=sheet.getRow(i);
				HSSFCell hcell=hrow.getCell(1);
				
				try {
					customer.setCname(hcell.getStringCellValue());
					hcell=hrow.getCell(2);
					String phone = (int)hcell.getNumericCellValue()+"";
					Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");  
					Matcher m = p.matcher(phone);  
					if(!m.matches()){
						request.setAttribute("error", "手机号格式错误");
						return "errors/error";
					};
					customer.setPhone(phone);
					hcell=hrow.getCell(3);
					String email = hcell.getStringCellValue()+"";
					Pattern p1 = Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");
					Matcher m1 = p1.matcher(email);  
					if(!m1.matches()){
						request.setAttribute("error", "email格式错误");
						return "errors/error";
					};
					customer.setEmail(hcell.getStringCellValue());
					
					hcell=hrow.getCell(4);
					customer.setProductLabel((int)hcell.getNumericCellValue()+"");
					hcell=hrow.getCell(5);
					customer.setRegionalId((int)hcell.getNumericCellValue()+"");
					
	
					customer.setAddTime(sf.format(new Date()));
					customer.setCusId(UUID.randomUUID().toString());
					customer.setIsAllot(CustomerManage.ALLOT_NO);
					customer.setIsReDevel(CustomerManage.TWICE_NO);
					customer.setCustomerType(CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
					customer.setCustomerSource("400");
					customer.setPusherId("system");
					customer.setPushType(CustomerManage.PUSH_TYPE_SYSTEM);
				} catch(Exception e) {
					request.setAttribute("error", "数据格式错误");
					return "errors/error";
				}
				//如果有相同的客户 则不进行分配
				if(customAllotService.getCheckReportedCount(customer)!=0) {
					request.setAttribute("error", "表格中含有相同的客户 该客户是："+customer.getCname());
					return "errors/error";
				}
				//如果客户主要数据为空 则数据格式错误 不进行导入
				if(!packageLeadingCustomerData(customer))
				{
					request.setAttribute("error", "数据格式错误");
					return "errors/error";
				}
				//进行分配
				customAllotService.allot(customer, CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
			}
		}
		//EXCEL2007以后版本
		else if(doName.equals("xlsx")) {
			XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream(path+picName));
			XSSFSheet sheet=workbook.getSheetAt(0);
			int size = sheet.getLastRowNum();
			for(int i=1;i<=size;i++) {
				XSSFRow row=sheet.getRow(i);
				XSSFCell cell=row.getCell(1);
				try {
					customer.setCname(cell.getStringCellValue());
					cell=row.getCell(2);
					customer.setPhone((int)cell.getNumericCellValue()+"");
					cell=row.getCell(3);
					customer.setEmail(cell.getStringCellValue());
					cell=row.getCell(4);
					customer.setProductLabel((int)cell.getNumericCellValue()+"");
					cell=row.getCell(5);
					customer.setRegionalId((int)cell.getNumericCellValue()+"");
					
					customer.setAddTime(sf.format(new Date()));
					customer.setCusId(UUID.randomUUID().toString());
					customer.setIsAllot(CustomerManage.ALLOT_NO);
					customer.setIsReDevel(CustomerManage.TWICE_NO);
					customer.setCustomerSource("400");
					customer.setPusherId("system");
					customer.setPushType(CustomerManage.PUSH_TYPE_SYSTEM);
					customer.setCustomerType(CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
				} catch(Exception e) {
					request.setAttribute("error", "数据格式错误");
					return "errors/error";
				}
				//如果有相同的客户 则不进行分配
				if(customAllotService.getCheckReportedCount(customer)!=0) {
					request.setAttribute("error", "表格中含有相同的客户 该客户是："+customer.getCname());
					return "errors/error";
				}
				//如果客户主要数据为空 则数据格式错误 不进行导入
				if(!packageLeadingCustomerData(customer))
				{
					request.setAttribute("error", "数据格式错误");
					return "errors/error";
				}
				//进行分配
				customAllotService.allot(customer, CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
			}
		}
		else {
			request.setAttribute("error", "格式错误，只能导入EXECL文件");
			return "errors/error";
		}
		request.setAttribute("success", "导入完成");
		return "errors/success";
	}
	/**
	 * 
	 * 功能描述：分配400乐语客户
	 *
	 * @param request
	 * @param response
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws Exception 
	 * @since 2014年3月11日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@RequestMapping("/allotNotRegisterCustomer")
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false)
	public String allotNotRegisterCustomer(HttpServletRequest request,HttpServletResponse response,String name,String phone,String email,String regionalId,String productLabel) throws Exception {
		PrintWriter out=response.getWriter();
		Emp emp = (Emp)request.getSession().getAttribute("currentUser");
		Customer customer=new Customer();
		//封装数据
		customer.setRegionalId(regionalId);
		customer.setProductLabel(productLabel);
		customer.setCname(name);
		if(phone.equals(""))
			phone="未填写";
		customer.setPhone(phone);
		if(email.equals(""))
			email="未填写";
		customer.setEmail(email);
		
		customer.setAddTime(sf.format(new Date()));
		customer.setCusId(UUID.randomUUID().toString());
		customer.setIsAllot(CustomerManage.ALLOT_NO);
		customer.setIsReDevel(CustomerManage.TWICE_NO);
		customer.setCustomerSource("400");
		customer.setPusherId(emp.getEmpno());
		customer.setPushType(CustomerManage.PUSH_TYPE_PERSON);
		customer.setCustomerType(CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
		//如果有相同的客户 则不进行分配
		if(customAllotService.getCheckAlikeCustomer(customer)!=null) {
			out.print("表格中含有相同的客户");
			return null;
		}
		//进行分配
		customAllotService.allot(customer, CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
		if(AppGlobalContainer.is400AllotMap.get("controler")!=null && AppGlobalContainer.is400AllotMap.get("controler").equals("notAllot")){
			customAllotService.delCustomer(customer.getCusId());
			AppGlobalContainer.is400AllotMap.clear();
			out.print("未添加成功，所在部门没有销售可以分配！");
			
			
		} else {
			out.print(1);
		}
		/*List<EmpCustomRelation>  ecrList = empCustomRelationService.getEmpCustomRelationByCusId(customer.getCusId());
		if(ecrList!=null && ecrList.size()>0){
			out.print(1);
		} else {
			customAllotService.delCustomer(customer.getCusId());
			out.print("未添加成功，所在部门没有销售可以分配！");
		}*/
		
		return null;
	}
	/**
	 * 
	 * 功能描述：打开添加400乐语客户页面
	 *
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年3月11日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	@RequestMapping("/show400Customer")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String show400Customr(HttpServletRequest request) {
		//取得地域list
		List<Area> areaList=areaService.getAreaOfClassA();
		//取得二级地域list
		List<Area> areaListClassB=areaService.getAreaOfClassA();
		//取得产品list
		List<Product> productList=productService.queryEnableProduct();
		//封装Map
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("area", areaList);
		map.put("areaClassB", areaListClassB);
		map.put("product", productList);
		//放入request
		request.setAttribute("selectMap", map);
		return "market/util/add400customer";
	}
	/**
	 * 
	 * 
	 * 功能描述：取得二级区域
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年4月30日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 *
	 */
	@ResponseBody
	@RequestMapping("/changeAreaForClassB")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String changeAreaForClassB(HttpServletRequest request,HttpServletResponse response,String areaId) throws IOException {
		PrintWriter out=response.getWriter();
		List<Area> areaList=areaService.getAreaOfClassByParentId(areaId);
		JSONArray json=null;
		if(areaList!=null) {
			json=JSONArray.fromObject(areaList);
		}
		out.print(json);
		return null;
	}
	/**
	 * 
	 * 功能描述：判断客户对象属性格式
	 *
	 * @param customer
	 * @return
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 *
	 * @since 2014年2月27日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	private boolean packageLeadingCustomerData(Customer customer) {
		if(
				customer.getCname()==null||
				customer.getRegionalId()==null||
				customer.getProductLabel()==null||
				customer.getCname().equals("")||
				customer.getRegionalId().equals("")||
				customer.getProductLabel().equals(""))
			return false;
		return true;
	}
	/**
	 * 
	 * 
	 * 功能描述：打开导出业绩页面
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年4月30日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 *
	 */
	@RequestMapping("/showExp")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String showExp(HttpServletRequest request,HttpServletResponse response) {
		return "market/util/expPerform";
	}
	
	/**
	 * 
	 * 
	 * 功能描述：打开业绩报表页面
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年4月30日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 *
	 */
	@RequestMapping("/showReportExp")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String showReportExp(HttpServletRequest request,HttpServletResponse response) {
		return "market/util/expforms";
	}
	
	/**
	 * 
	 * 
	 * 功能描述：打开业绩报表页面
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年4月30日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 *
	 */
	@RequestMapping("/show400Exp")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String show400Exp(HttpServletRequest request,HttpServletResponse response) {
		return "market/util/exp400form";
	}
	
	/**
	 * 
	 * 
	 * 功能描述：导出业绩数据
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年4月30日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 *
	 */
	@RequestMapping("/expPerform")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String expPerform(HttpServletRequest request,HttpServletResponse response,String timeUp,String timeDown) {
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/temp");
		File pathFile=new File(path);
		if(!pathFile.exists()) {
			pathFile.mkdirs();
		}
		String fileName=UUID.randomUUID().toString()+"_导出业绩.xls";
		File file=new File(path,fileName);
		
		if(file.exists()) {
			request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
			return "errors/error";
		}
		else {
			try {
				HSSFWorkbook ws = new HSSFWorkbook();//建立新HSSFWorkbook对象  
			    FileOutputStream fileOut = new FileOutputStream(path+sep+fileName);//创建文件流  
			    ws.write(fileOut);//把Workbook对象输出到路径path中  
			    fileOut.close();
				HSSFWorkbook book=doExpPerFormData(timeUp,timeDown,path+sep+fileName);
				if(book==null) {
					request.setAttribute("error", "该时间区间没有数据需要导出");
					return "errors/error";
				}
				book.write(new FileOutputStream(path+sep+fileName));
				
				//设置下载文件名
				String url=java.net.URLDecoder.decode(path+sep+fileName,"UTF-8");
				fileName=fileName.substring(fileName.lastIndexOf("_")+1);
				fileName=URLEncoder.encode(fileName, "UTF-8");
				response.addHeader("content-disposition","attachment;filename="+fileName);
				response.setHeader("content-type","text/html;charset=utf-8");
				response.setContentType("application/x-download");
				request.setCharacterEncoding("UTF-8");
				//下载操作
				File downLoadFile=new File(url);
				OutputStream out=response.getOutputStream();
				InputStream in=new FileInputStream(downLoadFile);
				byte[] b=new byte[1024];
				@SuppressWarnings("unused")
				int ch=0;
				while((ch=in.read(b))!=-1) {
					out.write(b,0,b.length);
				}
				in.close();
				return null;
			} catch (IOException e) {
				request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
				return "errors/error";
			}
		}
	}
	
	
	public HSSFWorkbook doExpPerFormData(String timeUp,String timeDown,String path) {
		try {
			List<CustomStateHist> list=customerStateHistService.getCshByTime(timeUp,timeDown);
			if(list==null || list.isEmpty()) {
				return null;
			}
			HSSFWorkbook book=new HSSFWorkbook(new FileInputStream(new File(path)));
			//创建excel文件对象  
	        HSSFSheet sheet = book.createSheet();
	        //创建第一行  
	        HSSFRow headRow = sheet.createRow(0);
	        //创建第一个单元格
	        HSSFCell headCell = headRow.createCell(0);
	        headCell.setCellValue("销售名");
	        headCell= headRow.createCell(1);
	        headCell.setCellValue("销售账号");
	        headCell= headRow.createCell(2);
	        headCell.setCellValue("会员账号");
	        headCell= headRow.createCell(3);
	        headCell.setCellValue("会员名");
	        headCell= headRow.createCell(4);
	        headCell.setCellValue("开始时间");
	        headCell= headRow.createCell(5);
	        headCell.setCellValue("结束时间");
	        headCell= headRow.createCell(6);
	        headCell.setCellValue("产品");
	        headCell= headRow.createCell(7);
	        headCell.setCellValue("备注");
	        // 文件头字体  
//	        Font font = book.createFont();
//	        font.setFontName("宋体");  
//	        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//	        font.setItalic(false);
//	        font.setFontHeight((short)200);
	        for(int i=1;i<list.size();i++) {
	        	CustomStateHist csh=list.get(i);
				// 创建第一行
				HSSFRow row = sheet.createRow(i);
				// 创建第一个单元格
				HSSFCell cell = row.createCell(0);
				cell.setCellValue(csh.getEname());
				cell = row.createCell(1);
				cell.setCellValue(csh.getLoginName());
				cell = row.createCell(2);
				cell.setCellValue(csh.getCustomId());
				cell = row.createCell(3);
				cell.setCellValue(csh.getCname());
				cell = row.createCell(4);
				cell.setCellValue(csh.getStartTime());
				cell = row.createCell(5);
				cell.setCellValue(csh.getEndTime());
				cell = row.createCell(6);
				cell.setCellValue(csh.getProductName());
				cell = row.createCell(7);
				cell.setCellValue(csh.getPushDesc());
	        }
	        return book;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 *
	 * 功能描述：业绩报表
	 * 
	 * @author 湛智
	 *
	 * @throws 2014年8月6日
	 *
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@RequestMapping("/expReportForms")
	public String ExpReportForms(HttpServletRequest request,HttpServletResponse response,String timeUp,String timeDown) {
		try {
			//创建临时Excel
			String path=request.getSession().getServletContext().getRealPath("/WEB-INF/temp");
			File pathFile=new File(path);
			if(!pathFile.exists()) {
				pathFile.mkdirs();
			}
			String fileName=UUID.randomUUID().toString()+"_导出报表.xls";
			File file=new File(path,fileName);
			if(file.exists()) {
				request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
				return "errors/error";
			}
			//计算报表逻辑
			List<Emp> empList=empService.getAllEmpList();
			List<Emp> resultList=new ArrayList<Emp>();
			for(Emp emp:empList) {
				emp.setTimeUp(timeUp);
				emp.setTimeDown(timeDown);
				List<CustomStateHist> cshList=customerStateHistService.getCshByTimeAndEmpno(emp);
				
				if(cshList==null || cshList.isEmpty()) {
					continue;
				}
				
				List<EmpCustomRelation> serviceList = new ArrayList<EmpCustomRelation>();
				List<EmpCustomRelation> simpleList = new ArrayList<EmpCustomRelation>();
				List<EmpCustomRelation> allList = new ArrayList<EmpCustomRelation>();
				Double gold = 0.0;
				
				//需求去除
//				int nullEcrCount=0;
				for(CustomStateHist csh:cshList) {
					EmpCustomRelation ecr=empCustomRelationService.getEcrByPushHistIdAndPusherId(csh);
					if(ecr==null) {
//						nullEcrCount++;
						continue;
					}
					else if(ecr.getCustomType()==CustomerManage.SERVICE_CUSTOMER) {
						serviceList.add(ecr);
						List<CustomerCare> tempOrderList = orderService.getOrdersByCusIdAndProductCode(ecr.getCustomId(), ecr.getProductCode());
						if(tempOrderList != null && !tempOrderList.isEmpty() && tempOrderList.get(0) != null) {
							
							Emp tempEmp = empService.getEmpbyEmpno(ecr.getEmpId());
							//销售部门
							tempEmp.setDname(deptService.getDeptByDeptId(emp.getId()).getDname());
							//角色
							tempEmp.setRoleName(roleService.getRoleById(emp.getRolId()).getName());
							//会员ID
							tempEmp.setCusId(ecr.getCustomId());
							//意向产品
							tempEmp.setProductName(customAllotService.getProductByProductCode(ecr.getProductCode()).getProductName());
							//接收人
							tempEmp.setPusherEmp(empService.getEmpbyEmpno(ecr.getEmpId()).getEname());
							//成单率
							/*tempEmp.setPlaceRate((double)serviceList.size()/((double)allList.size()+nullEcrCount));*/
							//推送日期
							tempEmp.setPushDate(sf.format(ecr.getCreateTime()));
							
							for(CustomerCare cc:tempOrderList) {
								gold += cc.getGoodsPrice();
								//成单日期
								tempEmp.setBuyDate(sf.format(cc.getBuyDate()));
								//商品名称
								tempEmp.setGoodsName(cc.getGoodsName());
							}
							
							//成单金额
							tempEmp.setGold(gold);
							
							resultList.add(tempEmp);
						}
					}
					else {
						simpleList.add(ecr);
					}
					allList.add(ecr);
				}
			}
			
			HSSFWorkbook ws = new HSSFWorkbook();//建立新HSSFWorkbook对象  
		    FileOutputStream fileOut = new FileOutputStream(path+sep+fileName);//创建文件流  
		    ws.write(fileOut);//把Workbook对象输出到路径path中  
		    fileOut.close();
			HSSFWorkbook book=doExpReportForms(resultList,path+sep+fileName);
			if(book==null) {
				request.setAttribute("error", "该时间区间没有推送数据需要导出");
				return "errors/error";
			}
			book.write(new FileOutputStream(path+sep+fileName));
			
			//设置下载文件名
			String url=java.net.URLDecoder.decode(path+sep+fileName,"UTF-8");
			fileName=fileName.substring(fileName.lastIndexOf("_")+1);
			fileName=URLEncoder.encode(fileName, "UTF-8");
			response.addHeader("content-disposition","attachment;filename="+fileName);
			response.setHeader("content-type","text/html;charset=utf-8");
			response.setContentType("application/x-download");
			request.setCharacterEncoding("UTF-8");
			//下载操作
			File downLoadFile=new File(url);
			OutputStream out=response.getOutputStream();
			InputStream in=new FileInputStream(downLoadFile);
			byte[] b=new byte[1024];
			@SuppressWarnings("unused")
			int ch=0;
			while((ch=in.read(b))!=-1) {
				out.write(b,0,b.length);
			}
			in.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public HSSFWorkbook doExpReportForms(List<Emp> list,String path) {
		try {
			if(list==null || list.isEmpty()) {
				return null;
			}
			HSSFWorkbook book=new HSSFWorkbook(new FileInputStream(new File(path)));
			//创建excel文件对象  
	        HSSFSheet sheet = book.createSheet();
	        //创建第一行  
	        HSSFRow headRow = sheet.createRow(0);
	        //创建第一个单元格
	        HSSFCell headCell = headRow.createCell(0);
	        headCell.setCellValue("员工姓名");
	        headCell= headRow.createCell(1);
	        headCell.setCellValue("所属部门");
	        headCell= headRow.createCell(2);
	        headCell.setCellValue("角色");
	        headCell= headRow.createCell(3);
	        headCell.setCellValue("会员号");
	        headCell= headRow.createCell(4);
	        headCell.setCellValue("意向商品");
	        headCell= headRow.createCell(5);
	        headCell.setCellValue("接受人");
	        headCell= headRow.createCell(6);
	        headCell.setCellValue("推送日期");
	        headCell= headRow.createCell(7);
	        headCell.setCellValue("成单日期");
	        headCell= headRow.createCell(8);
	        headCell.setCellValue("商品名称");
	        headCell= headRow.createCell(9);
	        headCell.setCellValue("成单金额");
	        // 文件头字体  
//	        Font font = book.createFont();
//	        font.setFontName("宋体");  
//	        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//	        font.setItalic(false);
//	        font.setFontHeight((short)200);
	        for(int i=1;i<list.size();i++) {
	        	Emp emp=list.get(i);
				// 创建第一行
				HSSFRow row = sheet.createRow(i);
				// 创建第一个单元格
				HSSFCell cell = row.createCell(0);
				cell.setCellValue(emp.getEname());
				cell = row.createCell(1);
				cell.setCellValue(emp.getDname());
				cell = row.createCell(2);
				cell.setCellValue(emp.getRoleName());
				cell = row.createCell(3);
				cell.setCellValue(emp.getCusId());
				cell = row.createCell(4);
				cell.setCellValue(emp.getProductName());
				cell = row.createCell(5);
				cell.setCellValue(emp.getEname());
				cell = row.createCell(6);
				cell.setCellValue(emp.getPushDate());
				cell = row.createCell(7);
				cell.setCellValue(emp.getBuyDate());
				cell = row.createCell(8);
				cell.setCellValue(emp.getGold());
	        }
	        return book;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * 
	 * 功能描述：导出业绩数据
	 *
	 * @author 王湛智[wangzhanzhi@xinnet.com]
	 * @throws IOException 
	 *
	 * @since 2014年4月30日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 *
	 */
	@RequestMapping("/exp400form")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	public String exp400form(HttpServletRequest request,HttpServletResponse response,String timeUp,String timeDown) {
		String path=request.getSession().getServletContext().getRealPath("/WEB-INF/temp");
		File pathFile=new File(path);
		if(!pathFile.exists()) {
			pathFile.mkdirs();
		}
		String fileName=UUID.randomUUID().toString()+"_导出业绩.xls";
		File file=new File(path,fileName);
		
		if(file.exists()) {
			request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
			return "errors/error";
		}
		else {
			try {
				HSSFWorkbook ws = new HSSFWorkbook();//建立新HSSFWorkbook对象  
			    FileOutputStream fileOut = new FileOutputStream(path+sep+fileName);//创建文件流  
			    ws.write(fileOut);//把Workbook对象输出到路径path中  
			    fileOut.close();
				HSSFWorkbook book=doExp400FormData(timeUp,timeDown,path+sep+fileName);
				if(book==null) {
					request.setAttribute("error", "该时间区间没有数据需要导出");
					return "errors/error";
				}
				book.write(new FileOutputStream(path+sep+fileName));
				
				//设置下载文件名
				String url=java.net.URLDecoder.decode(path+sep+fileName,"UTF-8");
				fileName=fileName.substring(fileName.lastIndexOf("_")+1);
				fileName=URLEncoder.encode(fileName, "UTF-8");
				response.addHeader("content-disposition","attachment;filename="+fileName);
				response.setHeader("content-type","text/html;charset=utf-8");
				response.setContentType("application/x-download");
				request.setCharacterEncoding("UTF-8");
				//下载操作
				File downLoadFile=new File(url);
				OutputStream out=response.getOutputStream();
				InputStream in=new FileInputStream(downLoadFile);
				byte[] b=new byte[1024];
				@SuppressWarnings("unused")
				int ch=0;
				while((ch=in.read(b))!=-1) {
					out.write(b,0,b.length);
				}
				in.close();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				request.setAttribute("error", "导出失败 请重新尝试 (如连续失败多次请联系开发人员)");
				return "errors/error";
			}
		}
	}
	
	public HSSFWorkbook doExp400FormData(String timeUp,String timeDown,String path) {
		try {
			List<CustomStateHist> list=customerStateHistService.getCshByTimeAndCustomerType(timeUp,timeDown,CustomerManage.NOT_REGISTER_NEW_CUSTOMER);
			if(list==null || list.isEmpty()) {
				return null;
			}
			HSSFWorkbook book=new HSSFWorkbook(new FileInputStream(new File(path)));
			//创建excel文件对象  
	        HSSFSheet sheet = book.createSheet();
	        //创建第一行  
	        HSSFRow headRow = sheet.createRow(0);
	        //创建第一个单元格
	        HSSFCell headCell = headRow.createCell(0);
	        headCell.setCellValue("临时编号");
	        headCell= headRow.createCell(1);
	        headCell.setCellValue("录入日期");
	        headCell= headRow.createCell(2);
	        headCell.setCellValue("录入人");
	        headCell= headRow.createCell(3);
	        headCell.setCellValue("接收人");
	        // 文件头字体  
//	        Font font = book.createFont();
//	        font.setFontName("宋体");  
//	        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//	        font.setItalic(false);
//	        font.setFontHeight((short)200);
	        for(int i=0;i<list.size();i++) {
	        	CustomStateHist csh=list.get(i);
	        	Emp pusherEmp = empService.getEmpbyEmpno(csh.getEmpId());
	        	Emp pushEmp = empService.getEmpbyEmpno(csh.getPusherId());
	        	Customer customer = customAllotService.getCustomerById(csh.getCustomId());
	        	if(pusherEmp == null || pushEmp == null || customer == null) {
	        		continue;
	        	}
				// 创建第一行
				HSSFRow row = sheet.createRow(i+1);
				// 创建第一个单元格
				HSSFCell cell = row.createCell(0);
				cell.setCellValue(csh.getCustomId());
				cell = row.createCell(1);
				cell.setCellValue(customer.getAddTime());
				cell = row.createCell(2);
				cell.setCellValue(pushEmp.getEname());
				cell = row.createCell(3);
				cell.setCellValue(pusherEmp.getEname());
	        }
	        return book;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
